package com.cmcc.groupcontacts.firewall.activity;

import java.util.ArrayList;

import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.cmcc.groupcontacts.MainApp;
import com.cmcc.groupcontacts.MainApp.AfterBlockedCallbackEvent;
import com.cmcc.groupcontacts.common.CallReceiver;
import com.cmcc.groupcontacts.firewall.activity.strategy.ActivityTitleStrategy;
import com.cmcc.groupcontacts.firewall.adapter.CallListAdapter;
import com.cmcc.groupcontacts.firewall.business.CallListBusiness;
import com.cmcc.groupcontacts.firewall.business.FilterListBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.CallInfoVO;
import com.cmcc.groupcontacts.firewall.dao.model.CallListVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.IntentManager;
import com.cmcc.groupcontacts.util.StringUtil;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.yinhai.activity.R;

/**
 * 来电拦截记录Activity
 * 
 * @author
 * 
 */
public class CallListActivity extends BaseListActivity {
	private CallListBusiness callListBiz;

	private CallListVO clickedCall;

	@Override
	public void setTitleStrategy() {
		titleStrategy = new ActivityTitleStrategy(this);
	}

	@Override
	public void setTitleButtons() {
		// 左边的“返回”按钮
		getLeftLayout().addView(createBackButton());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.call_list_activity);

		init();
		load();
	}

	private void init() {
		// 添加通话记录观察者的回调事件
		MainApp.getCallCallbackEvents().add(new AfterBlockedCallbackEvent() {
			@Override
			public void invoke(Message msg) {
				load();
			}
		});
		// 其他初始化设置
		registerForContextMenu(getListView());
		setEmptyText("");
		getListView().setOnItemLongClickListener(
				new AdapterView.OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						clickedCall = (CallListVO) parent
								.getItemAtPosition(position);
						getListView().showContextMenu();
						return true;
					}
				});
	}

	private void load() {
		// 异步加载来电拦截记录
		new CallListLoadTask().execute((Void[]) null);
	}

	@Override
	protected void onResume() {
		super.onResume();

		clearCallNofitication();
	}

	/*
	 * 清除来电拦截系统通知
	 */
	private void clearCallNofitication() {
		NotificationManager notificationManager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);
		for (Integer notificationId : CallReceiver.notificationIdList) {
			notificationManager.cancel(notificationId);
		}
		CallReceiver.notificationIdList.clear();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO: 清空操作
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (!ValidationUtil.isNullOrEmpty(clickedCall.getName())) {
			menu.setHeaderTitle(StringUtil.format("{0}({1})",
					clickedCall.getName(), clickedCall.getNumber()));
		} else {
			menu.setHeaderTitle(clickedCall.getNumber());
		}
		menu.add(0, 1, Menu.NONE, "删除");
		menu.add(0, 2, Menu.NONE, "呼叫号码");
		menu.add(0, 3, Menu.NONE, "短信回复");
		menu.add(0, 4, Menu.NONE, "保存为联系人");
		menu.add(0, 5, Menu.NONE, "加入白名单");
		menu.add(0, 6, Menu.NONE, "加入黑名单");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Builder builder = new Builder(this);
			builder.setTitle(R.string.hint);
			builder.setMessage("确定要删除这条来电拦截记录吗？");
			builder.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();

							boolean isSuccessful = false;
							try {
								isSuccessful = (callListBiz.delete(clickedCall
										.getId()) > 0);
							} catch (Exception e) {
								ExceptionHandler.handle(e, "删除来电拦截记录时出错");
							}
							if (isSuccessful) {
								getBaseAdapter().getDataSource().remove(
										clickedCall);
								if (!getBaseAdapter().getDataSource().isEmpty()) {
									getBaseAdapter().notifyDataSetChanged();
								} else {
									setListAdapter(null);
								}
								Toast.makeText(CallListActivity.this,
										R.string.delete_ok, Toast.LENGTH_SHORT)
										.show();
							} else {
								Toast.makeText(CallListActivity.this,
										R.string.delete_fail,
										Toast.LENGTH_SHORT).show();
							}
						}
					});
			builder.setNegativeButton(R.string.cancel, null);
			builder.show();
			break;
		case 2:
			IntentManager.call(this, clickedCall.getNumber());
			break;
		case 3:
			IntentManager.sms(this, clickedCall.getNumber(), "");
			break;
		case 4:
			IntentManager.addToContacter(this, clickedCall.getNumber());
			break;
		case 5:
			addToFilterList(false);
			break;
		case 6:
			addToFilterList(true);
			break;
		}
		return super.onContextItemSelected(item);
	}

	private void addToFilterList(boolean isBlackList) {
		CallInfoVO callInfo = new CallInfoVO();
		callInfo.setNumber(clickedCall.getNumber());
		callInfo.setName(clickedCall.getName());
		if (new FilterListBusiness().insert(callInfo, isBlackList) >= 0) {
			Toast.makeText(CallListActivity.this, R.string.insert_ok,
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(CallListActivity.this, R.string.insert_fail,
					Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * 异步加载来电拦截记录
	 */
	private class CallListLoadTask extends
			AsyncTask<Void, Integer, ArrayList<CallListVO>> {
		@Override
		protected ArrayList<CallListVO> doInBackground(Void... params) {
			callListBiz = new CallListBusiness();
			return callListBiz.getCallList();
		}

		@Override
		protected void onPostExecute(ArrayList<CallListVO> calls) {
			if (!ValidationUtil.isNullOrEmpty(calls)) {
				setListAdapter(new CallListAdapter(CallListActivity.this, calls));
			} else {
				setListAdapter(null);
			}
		}
	}
}
